package com.core.initialize;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.MessageToByteEncoder;

import com.google.protobuf.MessageLite;

/**
 * 客户端编码
 * 将mymessage转成二进制
 * @author King
 *
 */
public class MssageToBytesEncode extends MessageToByteEncoder<Message>
{
	
	@Override
	public void close(ChannelHandlerContext ctx, ChannelPromise promise)
			throws Exception {
		super.close(ctx, promise);
	}

	
	
	@Override
	protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out)
			throws Exception {
		int lenth=Message.CLIENTMIN_LENGTH;
//		System.out.println("�߳�"+Thread.currentThread().getName());
		byte[] bytes =null;
		if(msg.getBody()!=null)
		{
			MessageLite body = msg.getBody();
			bytes = body.toByteArray();
			lenth+=bytes.length;
		}
		out.writeInt(lenth);
		out.writeShort(msg.getModule());
		out.writeShort(msg.getAction());
		out.writeByte(msg.getEncrypt());
		if(bytes!=null)
		{
			out.writeBytes(bytes);
		}
	}
}
